package com.tintintech.sendmail.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import com.tintintech.sendmail.Config;

public class SmtpServer {

	private Socket sock = null;
	private String ip;
	
	public SmtpServer(String targetIp, String toemail)
	{
		this.ip = targetIp;
		try {
			sock = new Socket();
			SocketAddress addr = new InetSocketAddress(this.ip, 25);
			int connectTimeOut = new Integer(Config.GLOBALS.get("connectTimeOut")).intValue();
			int keepaliveTimeOut = new Integer(Config.GLOBALS.get("keepaliveTimeOut")).intValue();
			sock.connect(addr, connectTimeOut);
			sock.setTcpNoDelay(true);
			/* 备注： http://www.cnblogs.com/jerrychoi/archive/2010/04/15/1712931.html */
//			sock.setSoLinger(true, connectTimeOut);
			sock.setSoTimeout(keepaliveTimeOut);
		} catch (IOException ioe) {
			System.out.println("create-socket-client-IOException # " + toemail);
//			ioe.printStackTrace();
		} catch (Throwable e)
		{
			System.out.println("create-socket-client-exception # " + toemail);
//			e.printStackTrace();
		}
	}
	
	
	public Socket getSocket()
	{
		return sock;
	}
	
	public void close()
	{
		if (sock != null)
		{
			try {
				sock.close();
				sock = null;
			}
			catch (IOException ioe) {}
			catch (Throwable e) {
				System.out.println("socket-client-close-err");
			}
		}
	}
}
